﻿/**
 * Created by XiaoLei on 2015/5/30.
 * QQ:296324745
 */
/**
 * 
 * @author ddd
 * @version 1.0.0 beta
 * @githud https://github.com/ddd702/dialog.d
 * @created 2015.8.30
 * 
 */

(function(global) {
    var root = typeof self === 'object' && self.self === self && self ||
        typeof global === 'object' && global.global === global && global ||
        this;
    root.D = {}; //在根对象下创建D
    D.utils = { //工具类
        version: '1.0.0',
        parent: this,
        dateFormat: function(timestamp, format) {
            var date = new Date(parseInt(timestamp, 10)),
                o = {
                    "M+": date.getMonth() + 1,
                    "d+": date.getDate(),
                    "h+": date.getHours(),
                    "m+": date.getMinutes(),
                    "s+": date.getSeconds(),
                    "q+": Math.floor((date.getMonth() + 3) / 3),
                    "S": date.getMilliseconds()
                };

            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            }

            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return format;
        },
        extend: function(obj1, obj2) { //浅度合并obj1，obj2并返回新对象
            var obj = {};
            var o1 = obj1;
            var o2 = this.clone(obj2);
            for (var prop in o1) {
                if (o2.hasOwnProperty(prop)) {
                    obj[prop] = o2[prop];
                    delete o2[prop];
                } else {
                    obj[prop] = o1[prop];
                }
            }
            for (var prop in o2) {
                obj[prop] = o2[prop];
            }
            return obj;
        },
        clone: function(obj) { //返回一个克隆的对象  
            var newObj = {};
            for (var prop in obj) {
                newObj[prop] = obj[prop];
            }
            return newObj;
        },
        render: function(str, data) {
            if (!str || !data) {
                return '';
            }
            return (new Function("obj",
                "var p=[];" +
                "with(obj){p.push('" +
                str
                .replace(/[\r\t\n]/g, " ")
                .replace(/\'/g, "\"")
                .split("<&").join("\t")
                .replace(/((^|&>)[^\t]*)'/g, "$1\r")
                .replace(/\t=(.*?)&>/g, "',$1,'")
                .split("\t").join("');")
                .split("&>").join("p.push('")
                .split("\r").join("\\'") + "');}return p.join('');"))(data);
        },
        setEvent: function(ele, eName, handler, useCapture) {
            /**
             * @description ['绑定浏览器事件']
             * @param {object,string,function,boolean} [ele,eName,handler,useCapture] [dom对象,事件名,事件处理函数,是否冒泡(默认是false)]
             * 
             */
            if (!useCapture) {
                var useCapture = false;
            }
            if (window.addEventListener) {
                ele.addEventListener(eName, handler, useCapture);
            } else if (window.attachEvent) {
                ele.attachEvent('on' + eName, handler);
            } else {
                console.log('无法绑定事件');
            }
        },
        delEvent: function(ele, eName, handler, useCapture) {
            /**
             * @description ['解绑浏览器事件']
             * @param {object,string,function} [ele,eName,handler] [dom对象,事件名,去除的事件处理函数]
             * 
             */
            if (window.removeEventListener) {
                ele.removeEventListener(eName, handler, useCapture);
            } else if (window.attachEvent) {
                ele.detachEvent('on' + eName, handler);
            } else {
                console.log('无法解绑事件');
            }
        },
        getRequest: function(params) {
            /**
             * 
             * @param  {params} [传入参数序列,如:name=ddd&age=24&sex=1,默认window.location.search.replace('?', '');]
             * @return {[array]}  [返回一个参数数组]
             */
            if (typeof params === undefined || params === null || typeof window === 'object') { //在浏览器端默认是？后面的参数
                params = window.location.search.replace('?', '');
            }
            var url = params; //获取url中"?"符后的字串
            var theRequest = new Object();
            var str = url;
            if (str.indexOf("&") != -1) {
                strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
                }
            } else {
                var key = str.substring(0, str.indexOf("="));
                var value = str.substr(str.indexOf("=") + 1);
                theRequest[key] = decodeURI(value);
            }
            return theRequest;
        }
    };

    if (typeof define === "function" && define.amd) {
        define("D", [], function() {
            return D;
        });
    }
}(window));

var pet = {

	//路径
	// path: "http://res.yc.cn/web/",
	// request: "http://www.yc.cn/",
	path: /yc.cn/.test(location.host)?"http://res.yc.cn/web/":"http://test.res.ycnuli.com/res/web/",
	request: /yc.cn/.test(location.host)?"http://www.yc.cn/":"http://www.ycnuli.com/",
    requestHttps: /yc.cn/.test(location.host) ? "https://www.yc.cn/" : "https://www.ycnuli.com/",
	banpage:10,

	//load js
	loadScript: function (url, callback) {
		var script = document.createElement("script");
		script.src = url;
		document.body.appendChild(script);
		script.onload = script.onreadystatechange = function() {
			if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
				if (callback) {
					callback();
				}
			}
		};
	},

	//cookie time:XX天
	setCookie: function (name, value, time) {
		var oDate = new Date();
		oDate.setDate(oDate.getDate()+time);
		document.cookie = name+"="+value+";expires="+oDate;
	},
	getCookie: function (name) {
		var arr = document.cookie.split("; ");
		for(var i=0; i<arr.length; i++){
			var arr2 = arr[i].split("=");
			if(arr2[0] == name){
				return arr2[1];
			}
		}
		return "";
	},
	removeCookie: function (name) {
		pet.setCookie(name,"",0);
	},
	queryString:function(key){
		return (document.location.search.match(new RegExp("(?:^\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1];
	},
	stripscript:function(key) {
		var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&;—|{}【】‘；：”“'。，、？]")
		var rs = "";
		for (var i = 0; i < key.length; i++) {
			rs = rs + key.substr(i, 1).replace(pattern, '');
		}
		return rs;
	},

	//移动端环境判断
	ua: navigator.userAgent,
	url: window.location.href,
	isMobile: navigator.userAgent.match(/AppleWebKit.*Mobile/i),
	isIos: navigator.userAgent.match(/iPhone|iPod|iPad/i),
	isAndroid: navigator.userAgent.match(/Android/i),
	isWeixin: navigator.userAgent.match(/MicroMessenger/i)
};


;(function($){
	$.fn.extend({
		//选项卡插件
		tabs: function(options){
			options = $.extend({
				tabMenu: ".tab-menu",
				tabCont: ".tab-cont",
				event: "click",
				classname: "selected",
				callback:null
			}, options);
			var self = $(this),
				menus = self.find(options.tabMenu).children(),
				conts = self.find(options.tabCont).children();
			menus.first().addClass(options.classname);
			conts.hide().first().show();
			menus.on(options.event, function(){
				var index = $(this).index();
				$(this).addClass(options.classname).siblings().removeClass(options.classname);
				conts.eq(index).show().siblings().hide();
				if(options.callback)
				{
					options.callback(this);
				}
			});
		},
		//多行文字超出隐藏
		clamp: function(options) {
			options = $.extend({
				num: 60	//多少个文字
			}, options);
			$(this).each(function () {
				var self = $(this),
					text = self.text(),
					textLength = text.length;
				if (textLength > options.num) {
					var result = text.substr(0, options.num) + "...";
					self.html(result);
				}
			});
		}
	});
})(jQuery);


$(function(){//事件
    var $fLink=$('.friend-link');
    if ($fLink.height()>30) {
        $fLink.append('<div class="f-switch">展开</div>').addClass('toggle');
        $('.f-switch').on('click', function(event) {
            event.preventDefault();
            /* Act on the event */
            $(this).parent().toggleClass('toggle');
        });
    }
   
})

//回到顶部
function goTop() {
	var win = $(window),
		winHeight = win.height(),
		btnTop = $("<a class='gotop' href='#'></a>").appendTo($("body"));
	win.on("scroll load resize", function () {
		var posTop = win.scrollTop();
		posTop > winHeight ? btnTop.show() : btnTop.hide();
	});
	btnTop.on("click", function () {
		$("html,body").animate({scrollTop: 0});
		return false;
	});
}
goTop();

function goSearch() {
	$("#bdcs-search-form-submit").click(function () {
		var key = $("#bdcs-search-form-input").val();
		key = encodeURI(encodeURI(pet.stripscript(key)));
		location.href = pet.request + "search.do?keyword=" + key;
	})
	$('#bdcs-search-form-input').bind('keypress', function (event) {
		if (event.keyCode == "13") {
			$("#bdcs-search-form-submit").click();
		}
	});
}
goSearch();

//提示下载APP
function tipsDownload() {
	var btnTips = $(".j-tips-download"),
		downloadLink = pet.request+"download/index.do",//btnTips.attr("href"),
		tipsPopupHtml = '\
		<div class="popup popup-tips-download">\
			<div class="popup-wrap">\
				<div class="hd">\
					<h2 class="title">下载有宠客户端，查看更多</h2>\
					<a class="close" href="javascript:;">&times;</a>\
				</div>\
				<div class="bd">\
					<p class="active-down">&nbsp;</p>\
					<p class="active-box">\
						<a class="go-download" href="' + downloadLink + '" target="_blank">去下载</a>\
						<a class="close" href="javascript:;">继续逛逛 </a>\
					</p>\
				</div>\
			</div>\
		</div>';
	btnTips.on("click", function () {
		if ($(".popup-tips-download").size() == 0) {
			$("body").append(tipsPopupHtml);
		}
		var tipsPopup = $(".popup-tips-download"),
			close = tipsPopup.find(".close");
		close.on("click", function () {
			tipsPopup.remove();
		});
		return false;
	});
	if ($(".j-tips-download").size() == 0) {
		$("body").append('<a href="#" style="display: none;" class="j-tips-download">down</a>');
	}
}
tipsDownload();


//剪切板加文章链接
function clipBoard() {
	if (!window.getSelection || !document.querySelector(".content")) return;	
    //获取选中的HTML
    var getSelectedContents = function () {
        if (window.getSelection) { //chrome、firefox
            var range = window.getSelection().getRangeAt(0);
            var container = document.createElement('div');
            container.appendChild(range.cloneContents());
            return container.innerHTML;
        } else if (document.selection) { //IE
            return document.selection.createRange().htmlText;
        }
    };
    document.querySelector(".content").addEventListener("copy", function(e) {
        var selection = window.getSelection(),
                copyUrl = location.href,
				elem = document.createElement("div");
		elem.innerHTML = getSelectedContents() + "<br/>" + "本文转自有宠网：" + copyUrl;
		elem.cssText = "position:absolute;left:-99999px;";
		document.body.appendChild(elem);
        selection.selectAllChildren(elem);
        setTimeout(function () {
            elem.remove();
        }, 0);
    });
}
clipBoard();

//百度统计代码
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = pet.url.indexOf("yc.cn") != -1 ? "//hm.baidu.com/hm.js?d7ed70c0611a1cb1249c6b79ef2f5951" : "//hm.baidu.com/hm.js?51928fe35afbc49d22c0daf9a01c6ffa";
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(hm, s);
})();
//cnzz
(function() {
  var hm = document.createElement("script");
  hm.src = pet.url.indexOf("yc.cn") != -1 ? "https://s95.cnzz.com/z_stat.php?id=1260806349&web_id=1260806349" : "https://s95.cnzz.com/z_stat.php?id=1260806840&web_id=1260806840";
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(hm, s);
})();
//for 测试
if(!/yc.cn/.test(location.host)){
    $('.authen-link').append('<span style="display:inline-block;position:relative;width:auto;"><a href="https://ss.knet.cn/verifyseal.dll?sn=e16040544010063001kf02000000&amp;ct=df&amp;a=1&amp;pa=0.1027386405367714" id="kx_verify" tabindex="-1" target="_blank" kx_type="图标式" style="display:inline-block;"><img src="http://rr.knet.cn/static/images/logo/cnnic.png" style="border:none;" oncontextmenu="return false;" alt="可信网站"></a></span>')
}
